<?php

namespace App\Model;

use Util\Elasticsearch;

/**
 * es 搜索
 */
class EsSearch
{
    const INDEX = 'contract';
    protected Elasticsearch $client;

    public function __construct()
    {
        $this->client = new Elasticsearch();
    }

    /**
     * 搜索
     * @param array $params
     * @return array
     */
    public function search(array $params): array
    {
        if (!isset($params['page'])) {
            $params['page'] = 1;
        }
        if (!isset($params['limit'])) {
            $params['limit'] = 20;
        }
        $res = $this->client->search(['search' => ['title' => $params['keyword']], 'index' => self::INDEX], $params['page'], $params['limit']);
        return [
            'total' => $res['hits']['total']['value'] ?? 0,
            'list' => $res['hits']['hits']
        ];
    }

    /**
     * 添加
     * @param array $params
     * @return array
     */
    public function add(array $params): array
    {
        return $this->client->indexEs(['index' => self::INDEX, 'id' => $params['id'], 'body' => $params['body']]);
    }
}
